<template>
	<view class="page-main">
		<!-- #ifdef APP-PLUS -->
		<uni-status-bar></uni-status-bar>
		<!-- #endif -->

		<view class="big-header" :style="displayBuildMode ? 'height: 180rpx' : ''">
			<view class="search-wrapper">
				<!-- #ifdef APP-PLUS || H5-->
				<view class="back-icon">
					<image src="../../static/z.png" class="image" @tap="back"></image>
				</view>
				<!-- #endif -->
				<view class="search-bar">
					<icon class="icon" type="search" size="14" color="#969799" />
					<input class="input" type="search" style="width: 100%" v-model="finalOpt.keyword"
						placeholder="请输入园区名或位置" @confirm="performSearch()" placeholder-style="color:#888888" />
				</view>
			</view>
			<view v-if="!displayBuildMode" style="background-color: white" class="two-tabs">
				<view :class="finalOpt.house_type === 1 ? 'active-tab' : 'inactive-tab'" @tap="rentHouse">
					<view class="text">租</view>
				</view>
				<view :class="finalOpt.house_type === 2 ? 'active-tab' : 'inactive-tab'" style="" @tap="sellHouse">
					<view class="text">售</view>
				</view>
			</view>

			<view style="background-color: white" class="options-wrapper">
				<view class="option-text" :class="{ activeBlueText: isOption1 }" @tap="showOption(1)">
					区域
					<image v-show="!isOption1" src="../../static/images/listPage/inactiveArrow.png" mode="aspectFit">
					</image>
					<image v-show="isOption1" src="../../static/images/listPage/activeArrow.png" mode="aspectFit">
					</image>
				</view>
				<view :style="
            displayBuildMode || finalOpt.house_type === 0
              ? 'color: #e2e2e2'
              : ''
          " class="option-text" :class="{ activeBlueText: isOption2 }" @tap="priceOption(2)">
					价格
					<image v-show="!isOption2" src="../../static/images/listPage/inactiveArrow.png" mode="aspectFit">
					</image>
					<image v-show="isOption2" src="../../static/images/listPage/activeArrow.png" mode="aspectFit">
					</image>
				</view>
				<view :style="displayBuildMode ? 'color: #e2e2e2' : ''" class="option-text"
					:class="{ activeBlueText: isOption3 }" @tap="showOption(3)">
					户型
					<image v-show="!isOption3" src="../../static/images/listPage/inactiveArrow.png" mode="aspectFit">
					</image>
					<image v-show="isOption3" src="../../static/images/listPage/activeArrow.png" mode="aspectFit">
					</image>
				</view>
				<view class="option-text" :style="displayBuildMode ? 'color: #e2e2e2' : ''"
					:class="{ activeBlueText: isOption4 }" @tap="showOption(4)">
					更多
					<image v-show="!isOption4" src="../../static/images/listPage/inactiveArrow.png" mode="aspectFit">
					</image>
					<image v-show="isOption4" src="../../static/images/listPage/activeArrow.png" mode="aspectFit">
					</image>
				</view>
				<view class="option-text" :class="{ activeBlueText: isOption5 }" @tap="showOption(5)">
					排列
					<image style="opacity: 0.4" v-show="!isOption5" src="../../static/px.png" mode="aspectFit"></image>
					<image v-show="isOption5" src="../../static/scot2.png" mode="aspectFit"></image>
				</view>
			</view>

			<view style="z-index: -1" class="options-widgets-wrapper">
				<uni-transition class="widget" :mode-class="['fade', 'slide-top']" :duration="animationTime"
					:show="isOption1">
					<region @confirm="performSearch" />
				</uni-transition>
				<uni-transition class="widget" :mode-class="['fade', 'slide-top']" :duration="animationTime"
					:show="isOption2">
					<price ref="priceComponent" :rent-sell="finalOpt.house_type" @confirm="performSearch" />
				</uni-transition>

				<uni-transition class="widget" :mode-class="['fade', 'slide-top']" :duration="animationTime"
					:show="isOption3" @change="change">
					<house-type @confirm="performSearch"></house-type>
				</uni-transition>
				<uni-transition class="widget" :mode-class="['fade', 'slide-top']" :duration="animationTime"
					:show="isOption4" @change="change">
					<more @touchmove.stop.prevent="handlePrevent" @confirm="performSearch"></more>
				</uni-transition>

				<uni-transition class="widget" :mode-class="['fade', 'slide-top']" :duration="animationTime"
					:show="isOption5" @change="change">
					<sort ref="sortComponent" :show-price="currentHouseType !== 0 || displayBuildMode"
						@confirm="performSearch" :displayBuildMode="displayBuildMode"></sort>
				</uni-transition>
			</view>
		</view>

		<s-pull-scroll class="list-page-scroll wrap" :down-offset="120" showDownSuccess="true" ref="pullScroll"
			:pullDown="onPullDown" :showUpFinish="false">

			<view class="scroll-f">
				<scroll-view scroll-y @scrolltolower="onPullUp" class="scroll_view follow-scroll">

					<block v-for="(item, index) in house_list" v-if="!displayBuildMode" :key="index">
						<template v-if="item.house_sell_type === 1 || item.house_sell_type === 2">
							<my-house-card :display-build-mode="displayBuildMode" :item="item"></my-house-card>
						</template>
						<template style="background-color: yellow;padding-top: 300rpx;"
							v-else-if="item.house_sell_type === 3">
							<my-house-card v-if="currentHouseType === 0 || currentHouseType === 1" :tag-name="'租'"
								:display-build-mode="displayBuildMode" :item="item"></my-house-card>
							<my-house-card v-if="currentHouseType === 0 || currentHouseType === 2" :tag-name="'售'"
								:display-build-mode="displayBuildMode" :item="item"></my-house-card>
						</template>
					</block>

					<uni-load-more v-show="showLoading" class="loadMore" :status="status" :class="{'scroll-loading': house_list == ''}"
						:icon-size="12" :content-text="contentText" />
				</scroll-view>
			</view>
		</s-pull-scroll>

		<!-- 遮罩 -->
		<view @touchmove.prevent>
			<uni-transition class="mask-main" @click="macktop" :mode-class="['fade']"
				:styles="{ ...maskClass, zIndex: '3' }" :show="optionWidgetShown">
			</uni-transition>
		</view>
	</view>
</template>

<script>
	import myHouseCard from '../../components/myHouseCard';
	import sHouseCard from '../../components/sHouseCard';
	import sort from './sort';
	import price from './price';
	import houseType from './houseType';
	import more from './more';
	import region from './region';
	import {
		appMixin,
		pullDownRefresh
	} from '../../util/reuse';
	import {
		transitionMixin
	} from '../../util/reuse/transitionMixin';
	import {
		commonToastOpt_noIcon,
		d_uniShowToast,
		FINE_LOCATION,
		getRouterParam,
		MY_LOCATION,
		SHORT_TOAST_DURATION,
		uniShowToast,
	} from '../../util/misc';
	import {
		BASE_API,
		ONLINE_SERVER_USER,
		uniRequest
	} from '../../util/network';
	import {
		uniGetStorageSync
	} from '../../util/funcs';
	import {
		USER_ORIENTED
	} from '../../util/config';
	import {
		TESTING
	} from '../../util/test';

	export default {
		mixins: [appMixin, transitionMixin],
		data() {
			return {
				showLoading: true,
				pageLoaded: false,
				requesting: true,
				status: 'loading', // 与下面一一对应
				contentText: {
					contentdown: '上拉加载更多', // more
					contentrefresh: '加载中', // loading
					contentnomore: '暂无更多了', // nomore
				},
				status2: 'loading', // 与下面一一对应
				contentText2: {
					contentdown: '上拉加载更多', // more
					contentrefresh: '加载中', // loading
					contentnomore: '暂无更多了', // nomore
				},
				pagi: {
					// pagi 需要根据自己的需要 在vue组件里面定义
					page: 1,
					pageSize: 7,
				},
				animationTime: 100,
				show: true,
				showedOptionIndex: TESTING ? 1 : 0, // 0 为没有显示任何一个筛选条件
				optionShow: true,
				build_list: [],
				house_list: [],
				displayBuildMode: false, // true 盘源列表, false 房源列表
				dictForBuildMode: {
					page: 1,
					pageSize: 10,
					province: [],
					city: [],
					area: [],
					//排序筛选 0 默认排序 1 新上房源优先 2 价格 3  (格式：[0,'asc'](正向) [0,'desc'](反向))
					sort: [0, 'asc'],
					gd_line_id: [],
					gd_station_id: [],
				},
				dictForHouseMode: {
					page: 1,
					pageSize: 10,
					province: [],
					city: [],
					area: [],
					// 排序筛选 0 默认排序, 1 新上房源优先, 2 价格, 3  面积
					sort: [0, 'asc'],
					house_type: 1, // 1 租房, 2 售房
				},
				dataCount: 0,
				finalOpt: {
					lat: '',
					lon: '',
					city: [],
					house_type: 1,
					keyword: '', // 搜索关键字
				},
			};
		},
		mounted() {
			this.initPageData(false);
		},
		components: {
			sHouseCard,
			sort,
			price,
			houseType,
			more,
			region,
			myHouseCard,
		},
		methods: {
			macktop() {
				this.onMaskTap(() => {
					this.showedOptionIndex = 0;
				})
			},

			initPageData(fromRefresh = true) {
				this.resetListData();
				this.status = 'loading';
				this.pagi.page = 1;
				let routerParam = getRouterParam();
				if (routerParam.hasOwnProperty('displayBuildMode')) {
					this.displayBuildMode = routerParam.displayBuildMode;
				}
				if (
					routerParam.hasOwnProperty('searchKeyword') &&
					!this.displayBuildMode
				) {
					this.finalOpt.keyword = routerParam.searchKeyword;
				}
				// 设置城市
				let {
					city
				} = uniGetStorageSync(MY_LOCATION);
				//  设置精确定位
				let fineLocation = uniGetStorageSync(FINE_LOCATION);
				if (fineLocation && fineLocation.city === city) {
					if (fineLocation.location) {
						this.finalOpt.lat = fineLocation.location.lat;
						this.finalOpt.lon = fineLocation.location.lng;
					}
					// console.log('精确定位 using:', this.finalOpt)
				}

				this.finalOpt.city.push(city);
				//  租售列表, 选择租
				this.getListData({}, false, this.$refs.pullScroll);
				this.heatSearch();
			},

			resetListData() {
				this.build_list = [];
				this.house_list = [];
			},

			handlePrevent() {},

			// 下拉刷新
			onPullDown() {
				this.showLoading = false;
				this.initPageData();
			},

			// 上拉加载
			onPullUp() {
				if (this.status === 'nomore') return;
				this.pagi.page += 1;
				this.status = "loading";
				this.getListData({}, false, this.$refs.pullScroll, true);
			},

			change() {},

			performSearch(opt) {
				this.resetDataForComponents();
				this.showedOptionIndex = 0;
				this.heatSearch();
				this.getListData(opt, false, this.$refs.pullScroll);
			},

			// 搜索热度填加
			heatSearch() {
				let postData = {
					...this.pagi,
					...this.finalOpt
				};
				if (this.finalOpt.keyword == '') return
				this.$uniRequest('/search', postData).then((data) => {
					console.log("data", data);
				})
			},

			checkCanChange() {
				//不在请求数据的时候才能改变要看 租还是售列表
				let canChange = !this.requesting;
				if (this.showedOptionIndex !== 0) {
					canChange = false;
					uniShowToast('请先完成选择', false);
				}
				// console.log(canChange)
				return canChange;
			},

			// 清空已有选项
			resetOptions() {
				// 清空价格组件弄出来option
				this.$refs.priceComponent.clearSelection();
				delete this.finalOpt.house_price;
				delete this.finalOpt.house_sell_price;
				// 清空排列组件
				// console.log(  this.$refs.sortComponent)
				// this.$refs.sortComponent = 1
			},

			rentHouse() {
				if (!this.checkCanChange()) {} else {
					this.resetOptions();
					this.resetDataForComponents();
					if (this.finalOpt.house_type === 1) {
						this.$set(this.finalOpt, 'house_type', 0);
						// this.finalOpt.house_type = 0
					} else {
						this.$set(this.finalOpt, 'house_type', 1);
					}
					this.getListData({}, false, this.$refs.pullScroll);
				}
			},

			sellHouse() {
				if (!this.checkCanChange()) {} else {
					this.resetOptions();
					this.resetDataForComponents();
					// console.log('for house_type: ',this.finalOpt)
					if (this.finalOpt.house_type === 2) {
						this.$set(this.finalOpt, 'house_type', 0);
					} else {
						this.$set(this.finalOpt, 'house_type', 2);
					}
					this.getListData({}, false, this.$refs.pullScroll);
				}
			},

			priceOption(num) {
				if (this.finalOpt.house_type === 0 && !this.displayBuildMode) {
					d_uniShowToast({
							title: '请选择租或者售',
						},
						false
					);
					return;
				}
				this.showOption(num);
			},
			showOption(num) {
				//
				if (num >= 2 && num <= 4 && this.displayBuildMode) {
					return;
				}
				if (this.showedOptionIndex === num) {
					this.showedOptionIndex = 0;
				} else {
					this.showedOptionIndex = num;
				}
			},
			changeOptionShow(flag) {
				this.optionShow = flag;
			},

			back() {
				uni.navigateBack();
			},

			resetDataForComponents() {
				// 子组件进行筛选操作, 需要将已有数据清空
				let originalData = this.$options.data();
				this.build_list = originalData.build_list;
				this.house_list = originalData.house_list;
				this.pagi = originalData.pagi;
			},

			// 下拉刷新
			async getListData(optForSearch, toShowToast = false, pullScroll) {
				let _this = this;
				let reqPro = [];
				this.requesting = true;
				let postOpt = {
					// 解构顺序由久到新
					..._this.postParam(),
					...this.finalOpt,
					...optForSearch,
					...this.pagi,
				};
				this.finalOpt = postOpt;
				// 首页更多房源跳转过来
				// let requestUrl = this.postUrl();

				uniRequest('', this.finalOpt, {
					url: this.postUrl(),
					success: ({
						data
					}) => {
						if (data.code && data.code === 200) {
							_this.setData(data);
							if (_this.pagi.pageSize > data.data.list.length) {
								_this.status = 'nomore';
								pullScroll.finish();
							} else {
								_this.status = 'more';
								pullScroll.success();
							}

							if (toShowToast) {
								d_uniShowToast({
										title: '加载成功',
									},
									false
								);
							}
						} else {
							_this.status = 'nomore';
							pullScroll.finish();
							d_uniShowToast({
									title: '加载失败',
								},
								false
							);
						}
					},fail: () => {
						_this.status = 'nomore';
						pullScroll.finish();
						d_uniShowToast({
								title: '网络异常',
							},
							false
						);
					},complete: () =>{
						this.showLoading = true;
					}
				});

			},

			/*
			async getListData(optForSearch, toShowToast = false) {
				let _this = this;
				let reqPro = [];
				this.requesting = true;
				let postOpt = {
					// 解构顺序由久到新
					..._this.postParam(),
					...this.finalOpt,
					...optForSearch,
					...this.pagi,
				};
				// console.log('postOpt: ', postOpt)
				reqPro.push(
					new Promise((resolve) => {
						if (this.finalOpt !== postOpt) {
							this.finalOpt = postOpt;
							// console.log(this.postUrl())
							this.status = 'loading';
							reqPro.push(
								new Promise((resolve) => {
									if (this.finalOpt.keyword && this.finalOpt.keyword !== '') {
										uniRequest(
											'/search', {
												keyword: this.finalOpt.keyword,
												city: uni.getStorageSync('MY_LOCATION').city
											}, {
												success: ({
													data
												}) => {
													console.log('request~');
													console.log('in search!', data);
													resolve();
												},
											}
										);
									} else {
										resolve();
									}
								})
							);

							// 请求数据
							uniRequest('', this.finalOpt, {
								url: this.postUrl(),
								success: ({
									data
								}) => {
									// console.log('final opt: ', this.finalOpt, data)

									// console.log('request~')
									resolve();
									if (data.code && data.code === 200) {
										_this.setData(data);
										if (toShowToast) {
											d_uniShowToast({
													title: '加载成功',
												},
												false
											);
										}
									} else {
										d_uniShowToast({
												title: '加载失败',
											},
											false
										);
									}
								},
							});
						} else {
							uni.showToast({
								...commonToastOpt_noIcon(),
								title: '刷新成功',
								duration: SHORT_TOAST_DURATION,
							});
							resolve();
						}
					})
				);

				return await Promise.all(reqPro);
			},
			*/

			postUrl() {
				if (this.displayBuildMode) {
					if (!USER_ORIENTED) {
						return ONLINE_SERVER_USER + '/build_list'; // 盘源统一使用用户端的接口
					}
					return BASE_API + '/build_list';
				} else {
					return BASE_API + '/list';
				}
			},
			postParam() {
				if (this.displayBuildMode) {
					return this.dictForBuildMode;
				} else {
					return this.dictForHouseMode;
				}
			},

			// 请求数据后, 设置build_list, house_list列表值
			setData({
				data
			}) {
				if (this.requesting && !this.pageLoaded) {
					this.build_list = [];
					this.house_list = [];
				}
				if (data.list.length < this.pagi.pageSize) {
					this.status = 'nomore';
				} else {
					this.status = 'more';
				}
				if (this.displayBuildMode) {
					this.build_list = this.build_list.concat(data.list);
				} else {
					this.house_list = this.house_list.concat(data.list);
				}
				this.dataCount = data.count;
				this.requesting = false;
				this.pageLoaded = true;
			},
		},
		computed: {
			currentHouseType() {
				// 允不允许同时在一个列表内展示两种租售卡片
				return this.finalOpt.house_type; // 0 全部 1 租 2 售
			},
			displayedContentDesc() {
				if (this.displayBuildMode) {
					return 'build';
				} else {
					return 'house';
				}
			},
			isOption1() {
				return this.showedOptionIndex === 1;
			},
			isOption2() {
				return this.showedOptionIndex === 2;
			},
			isOption3() {
				return this.showedOptionIndex === 3;
			},
			isOption4() {
				return this.showedOptionIndex === 4;
			},
			isOption5() {
				return this.showedOptionIndex === 5;
			},
			optionWidgetShown() {
				// if (this.showedOptionIndex !== 0) {
				//   setTimeout(() => {
				//     this.animationTime = 0
				//   }, ANIMATION_TIME + 10)
				//   return true
				// } else {
				//   this.animationTime = ANIMATION_TIME
				//   return false
				// }
				return this.showedOptionIndex !== 0;
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import 'common';

	.page-main {
		height: 100%;
		overflow: hidden;

		.options-widgets-wrapper {
			/*position: ;*/
			position: relative;

			.widget {
				position: absolute;
			}
		}

		.big-header {
			position: fixed;
			background: white;
			z-index: 5;
			height: 300rpx;
			@include borderBox;

			.search-wrapper {
				background-color: white;
				@include center;
				height: 88rpx;
				width: 100vw;

				.back-icon {
					margin-right: 6px;
					width: 38px;
					height: 38px;
					@include center;

					.image {
						width: 16px;
						height: 16px;
					}
				}

				.search-bar {
					border-radius: 20px;
					background-color: #f7f7f7;
					width: 320px;
					height: 40px;
					padding: 0 36rpx;
					@include borderBox;
					@include center;

					.icon {
						margin-right: 16rpx;
					}

					.input {
						font-size: 28rpx;
						color: #969799;
					}
				}
			}

			.two-tabs {
				max-height: 100vw;
				height: 124rpx;
				@include center;
				display: flex;
				justify-content: space-between;
				width: 100vw;
				padding: 0 42px;
				@include borderBox;

				.active-tab,
				.inactive-tab {
					position: relative;
					width: 248rpx;
					height: 90rpx;
					@include center;
					background-size: 224rpx auto;
					background-repeat: no-repeat;
					background-position: center top;
					background-image: url('../../static/images/listPage/rectangle-tip@3x.png');
					font-size: 30rpx;

					.text {
						position: absolute;
						top: 16 + 5rpx;
						color: white;
					}
				}

				.inactive-tab {
					top: -2rpx;
					background-image: url('../../static/images/listPage/inactive-rectangle@3x.png');

					.text {
						top: 18 + 5rpx;
						color: #323233;
					}
				}
			}

			.options-wrapper {
				max-width: 100vw;
				height: 88rpx;
				display: flex;
				align-items: center;
				text-align: center;
				background: white;
				@include borderBox;
				border-bottom: 1px solid $greyBorderColor;

				.activeBlueText {
					color: #004fbf;
				}

				.option-text {
					flex-grow: 1;
					font-size: 14px;

					image {
						width: 10px;
						height: 10px;
						margin: 0 5px;
						position: relative;
						top: 0px;
					}
				}
			}
		}

		.list-page-scroll {
			height: 100%;
			@include borderBox;
			display: flex;
			flex-direction: column;
			padding: 300rpx 30rpx 0;

		}
	}

	/deep/.loadMore {
		margin-bottom: 10px;
		padding-bottom: 0px;
	}

	.scroll-f {
		position: relative;
		height: calc(100vh - 150px - var(--status-bar-height));
		width: 100%;
	}

	.scroll_view {
		width: 100%;
		height: 100%;
	}

	/deep/.scroll-loading {
		padding-top: calc((100vh - 150px)/3);
		height: auto;
	}
</style>
